package edu.czjtu.geesonke_demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.czjtu.geesonke_demo.common.R;
import edu.czjtu.geesonke_demo.dto.DishDto;
import edu.czjtu.geesonke_demo.entity.Category;
import edu.czjtu.geesonke_demo.entity.Dish;
import edu.czjtu.geesonke_demo.service.CategoryService;
import edu.czjtu.geesonke_demo.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.save(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品信息分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name != null, Dish::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            return dish2dishDto(item);
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        Dish dish = dishService.getById(id);
        DishDto dishDto = dish2dishDto(dish);
        return R.success(dishDto);

    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        dishService.updateById(dishDto);

        return R.success("修改菜品成功");
    }

    /**
     * 修改状态，支持批量修改
     * @param status
     * @param ids
     * @return
     */
    @PutMapping("/status/{status}")
    public R<String> status(@PathVariable("status") Integer status, @RequestBody String ids) {
        log.debug("修改菜品ids:{} 的状态为：{}。", ids, status);

        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());

        UpdateWrapper<Dish> dishUpdateWrapper = new UpdateWrapper<>();
        dishUpdateWrapper.in("id", idList).set("status", status);

        dishService.update(dishUpdateWrapper);
        return R.success("更新成功");
    }

    /**
     * 列出符合类型的菜品
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            return dish2dishDto(item);
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }


    /**
     * 删除菜品，支持批量删除
     * @param ids
     * @return
     */
    @DeleteMapping()
    @Transactional
    public R<String> delete(@RequestParam("ids") String ids) {
        log.info("删除菜名ids：{}", ids);
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(item -> {
                    Long id = Long.valueOf(item);
                    dishService.removeById(id);
                    return id;
                })
                .collect(Collectors.toList());
        return R.success("删除菜品成功。");
    }

    /**
     * 将dish转化为dishDto
     *
     * @param dish
     * @return
     */
    private DishDto dish2dishDto(Dish dish) {
        DishDto dishDto = new DishDto();

        BeanUtils.copyProperties(dish, dishDto);

        Category category = categoryService.getById(dish.getCategoryId());

        if (category != null) {
            dishDto.setCategoryName(category.getName());
        }

        return dishDto;
    }
}
